package com.css.zfzx.sjcj.modules.hddcVolcanicSamplePoint.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.PlatformDateUtils;
import com.css.bpm.platform.utils.PlatformObjectUtils;
import com.css.bpm.platform.utils.PlatformPageUtils;
import com.css.bpm.platform.utils.PlatformSessionUtils;
import com.css.bpm.platform.utils.UUIDGenerator;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcVolcanicSamplePoint.repository.HddcVolcanicsamplepointNativeRepository;
import com.css.zfzx.sjcj.modules.hddcVolcanicSamplePoint.repository.HddcVolcanicsamplepointRepository;
import com.css.zfzx.sjcj.modules.hddcVolcanicSamplePoint.repository.entity.HddcVolcanicsamplepointEntity;
import com.css.zfzx.sjcj.modules.hddcVolcanicSamplePoint.service.HddcVolcanicsamplepointService;
import com.css.zfzx.sjcj.modules.hddcVolcanicSamplePoint.service.handler.VolcanicPoint2PointExcelImportVerifyHandler;
import com.css.zfzx.sjcj.modules.hddcVolcanicSamplePoint.viewobjects.HddcVolcanicsamplepointPageVO;
import com.css.zfzx.sjcj.modules.hddcVolcanicSamplePoint.viewobjects.HddcVolcanicsamplepointQueryParams;
import com.css.zfzx.sjcj.modules.hddcVolcanicSamplePoint.viewobjects.HddcVolcanicsamplepointVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @author zhangcong
 * @date 2020-11-27
 */
@Service
public class HddcVolcanicsamplepointServiceImpl implements HddcVolcanicsamplepointService {

    private final HddcVolcanicsamplepointRepository hddcVolcanicsamplepointRepository;
    private final HddcVolcanicsamplepointNativeRepository hddcVolcanicsamplepointNativeRepository;
    private final VolcanicPoint2PointExcelImportVerifyHandler volcanicPoint2PointExcelImportVerifyHandler;

    @Autowired
    public HddcVolcanicsamplepointServiceImpl(HddcVolcanicsamplepointRepository hddcVolcanicsamplepointRepository,
                                              HddcVolcanicsamplepointNativeRepository hddcVolcanicsamplepointNativeRepository,
                                              VolcanicPoint2PointExcelImportVerifyHandler volcanicPoint2PointExcelImportVerifyHandler) {
        this.hddcVolcanicsamplepointRepository = hddcVolcanicsamplepointRepository;
        this.hddcVolcanicsamplepointNativeRepository = hddcVolcanicsamplepointNativeRepository;
        this.volcanicPoint2PointExcelImportVerifyHandler = volcanicPoint2PointExcelImportVerifyHandler;
    }

    @Override
    public JSONObject queryHddcVolcanicsamplepoints(HddcVolcanicsamplepointQueryParams queryParams, int curPage, int pageSize, String sort, String order) {
        Page<HddcVolcanicsamplepointPageVO> hddcVolcanicsamplepointPage = this.hddcVolcanicsamplepointNativeRepository.queryHddcVolcanicsamplepoints(queryParams, curPage, pageSize, sort, order);
        return PlatformPageUtils.formatPageData(hddcVolcanicsamplepointPage);
    }

    @Override
    public HddcVolcanicsamplepointEntity getHddcVolcanicsamplepoint(String id) {
        return this.hddcVolcanicsamplepointRepository.findById(id).orElse(null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcVolcanicsamplepointEntity saveHddcVolcanicsamplepoint(HddcVolcanicsamplepointEntity hddcVolcanicsamplepoint) {
        String uuid = UUIDGenerator.getUUID();
        hddcVolcanicsamplepoint.setUuid(uuid);
        hddcVolcanicsamplepoint.setCreateUser(PlatformSessionUtils.getUserId());
        Timestamp now = PlatformDateUtils.getCurrentTimestamp();
        hddcVolcanicsamplepoint.setCreateTime(now);
        hddcVolcanicsamplepoint.setUpdateTime(now);
        hddcVolcanicsamplepoint.setIsValid("1");
        hddcVolcanicsamplepoint.setQualityinspectionStatus("0");
        hddcVolcanicsamplepoint.setExtends10("1");
        this.hddcVolcanicsamplepointRepository.save(hddcVolcanicsamplepoint);
        return hddcVolcanicsamplepoint;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcVolcanicsamplepointEntity updateHddcVolcanicsamplepoint(HddcVolcanicsamplepointEntity hddcVolcanicsamplepoint) {
        Optional<HddcVolcanicsamplepointEntity> oldItemOptional = hddcVolcanicsamplepointRepository.findById(hddcVolcanicsamplepoint.getUuid());
        if (!oldItemOptional.isPresent())
            return null;
        HddcVolcanicsamplepointEntity entity = oldItemOptional.get();
        UpdateUtil.copyNullProperties(entity, hddcVolcanicsamplepoint);
        hddcVolcanicsamplepoint.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcVolcanicsamplepoint.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcVolcanicsamplepointRepository.save(hddcVolcanicsamplepoint);
        return hddcVolcanicsamplepoint;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcVolcanicsamplepoints(List<String> ids) {
        List<HddcVolcanicsamplepointEntity> hddcVolcanicsamplepointList = this.hddcVolcanicsamplepointRepository.findAllById(ids);
        if (!PlatformObjectUtils.isEmpty(hddcVolcanicsamplepointList) && hddcVolcanicsamplepointList.size() > 0) {
            for (HddcVolcanicsamplepointEntity hddcVolcanicsamplepoint : hddcVolcanicsamplepointList) {
                hddcVolcanicsamplepoint.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcVolcanicsamplepoint.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcVolcanicsamplepoint.setIsValid("0");
                this.hddcVolcanicsamplepointRepository.save(hddcVolcanicsamplepoint);
            }
        }
    }

    /**
     * 逻辑删除-根据项目id删除数据
     */
    @Override
    public void deleteByProjectId(List<String> projectIds) {
        List<HddcVolcanicsamplepointEntity> hddcVolcanicsamplepointList = this.hddcVolcanicsamplepointRepository.queryHddcVolcanicsamplepointsByProjectId(projectIds);
        if (!PlatformObjectUtils.isEmpty(hddcVolcanicsamplepointList) && hddcVolcanicsamplepointList.size() > 0) {
            for (HddcVolcanicsamplepointEntity hddcVolcanicsamplepoint : hddcVolcanicsamplepointList) {
                hddcVolcanicsamplepoint.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcVolcanicsamplepoint.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcVolcanicsamplepoint.setIsValid("0");
                this.hddcVolcanicsamplepointRepository.save(hddcVolcanicsamplepoint);
            }
        }
    }

    /**
     * 逻辑删除-根据任务id删除数据
     */
    @Override
    public void deleteByTaskId(List<String> taskId) {
        List<HddcVolcanicsamplepointEntity> hddcVolcanicsamplepointList = this.hddcVolcanicsamplepointRepository.queryHddcVolcanicsamplepointsByTaskId(taskId);
        if (!PlatformObjectUtils.isEmpty(hddcVolcanicsamplepointList) && hddcVolcanicsamplepointList.size() > 0) {
            for (HddcVolcanicsamplepointEntity hddcVolcanicsamplepoint : hddcVolcanicsamplepointList) {
                hddcVolcanicsamplepoint.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcVolcanicsamplepoint.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcVolcanicsamplepoint.setIsValid("0");
                this.hddcVolcanicsamplepointRepository.save(hddcVolcanicsamplepoint);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        return PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
    }

    @Override
    public void exportFile(HddcVolcanicsamplepointQueryParams queryParams, HttpServletResponse response) {
        List<HddcVolcanicsamplepointEntity> yhDisasterEntities = hddcVolcanicsamplepointNativeRepository.exportYhDisasters(queryParams);
        List<HddcVolcanicsamplepointVO> list = new ArrayList<>();
        for (HddcVolcanicsamplepointEntity entity : yhDisasterEntities) {
            HddcVolcanicsamplepointVO yhDisasterVO = new HddcVolcanicsamplepointVO();
            BeanUtils.copyProperties(entity, yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list, "火山采样点-点", "火山采样点-点", HddcVolcanicsamplepointVO.class, "火山采样点-点.xls", response);
    }

    @Override
    public String importExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            params.setVerifyHandler(volcanicPoint2PointExcelImportVerifyHandler);
            // 获取到Excel数据
            ExcelImportResult<HddcVolcanicsamplepointVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcVolcanicsamplepointVO.class, params);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                for (HddcVolcanicsamplepointVO yhDisasterVO : result.getFailList()) {
                    returnMsg.append("第").append(yhDisasterVO.getRowNum()).append("行").append(yhDisasterVO.getErrorMsg()).append("<br/>");
                }
                if (returnMsg.length() > 0)
                    return returnMsg.toString();
            }
            List<HddcVolcanicsamplepointVO> list = result.getList();
            //保存
            saveDisasterList(list);
            return returnMsg.append("成功导入").append(result.getList().size()).append("条记录").toString();
        } catch (Exception e) {

            return "导入失败，请检查数据正确性";
        }
    }

    /**
     * 批量存入库表并且返回错误数量
     */
    public void saveDisasterList(List<HddcVolcanicsamplepointVO> list) {
        for (HddcVolcanicsamplepointVO hddcVolcanicsamplepointVO : list) {
            HddcVolcanicsamplepointEntity yhDisasterEntity = new HddcVolcanicsamplepointEntity();
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(hddcVolcanicsamplepointVO, yhDisasterEntity);
            saveHddcVolcanicsamplepoint(yhDisasterEntity);
        }
    }

}
